const poster = {
  /**
   * 绘制分享海报 
   * @param canvasId 
   * @param winWidth 宽度
   * @param winHeight 高度
   * @param imgs 主图以及二维码图
   *  格式 {mainPic: mainPic,qrcode: qrcode}
   * @param text 描述文字
   * @param name 程序名称
   **/
  drawPoster(canvasId, winWidth, winHeight, imgs, text, name, callback) {
    //获取绘图上下文 context
    let context = wx.createCanvasContext(canvasId)
    // 海报背景
    const grd = context.createLinearGradient(0, winWidth, winHeight, 0)
    grd.addColorStop(0, '#FFCB4B')
    grd.addColorStop(1, '#FFAE34')
    // Fill with gradient
    context.setFillStyle(grd);
    context.fillRect(0, 0, winWidth, winHeight);
    // 主图
    let width = 324,
      height = 387;
    context.drawImage(imgs.mainPic, (winWidth - width) / 2, 30, width, height)
    let a = 20 //定义行高
    context.setFontSize(15)
    context.setFillStyle("#f00")
    //名称很长调用方法将文字折行，传参 文字内容text，画布context
    let w = poster.getTextWidth(text, context) || 550
    let row = poster.wrapText(text, Math.floor(w / 2), context)
    for (let i = 0; i < row.length; i++) {
      context.fillText(row[i], (winWidth - w / 2) / 2, (winHeight + 230) / 2 + a * i)
    }
    // 识别小程序二维码 
    context.setFontSize(18)
    let w1 = poster.getTextWidth(name, context) || 140
    let x = (winWidth - w1 - 20 - 80) / 2;
    context.drawImage(imgs.qrcode, x, (winHeight + 380) / 2, 80, 80)
    context.setFillStyle("#152338")
    context.fillText(name, x + 80 + 20, (winHeight + 445) / 2)
    context.setFillStyle("#333")
    context.setFontSize(12)
    context.fillText('长按识别·立即体验', x + 80 + 20, (winHeight + 495) / 2)
    context.draw(false, () => {
      poster.createPoster(canvasId, winWidth, winHeight, (res) => {
        callback && callback(res)
      })
    })
  },
  /**
   *绘制商品海报 
   * @param canvasId 
   * @param winWidth 宽度
   * @param winHeight 高度
   * @param imgs 主图以及二维码图
   *  格式 {mainPic: mainPic,qrcode: qrcode}
   * @param text 商品名称
   * @param price 价格 格式 12.00，10.50
   * @param originalPrice 原价 格式 12.00，10.50
   * @param name 程序名称
   **/
  drawGoodsPoster(canvasId, winWidth, winHeight, imgs, text, price, originalPrice, name, callback) {
    let scaleRatio = 2
    //获取绘图上下文 context
    let context = wx.createCanvasContext(canvasId)
    // 海报背景
    const grd = context.createLinearGradient(0, winWidth, winHeight, 0)
    grd.addColorStop(0, '#FFFFFF')
    grd.addColorStop(1, '#FFFFFF')
    // Fill with gradient
    context.setFillStyle(grd);
    context.fillRect(0, 0, winWidth, winHeight);
    // 主图
    let width = 500 * scaleRatio / 2,
      height = 500 * scaleRatio / 2;
    context.drawImage(imgs.mainPic, (winWidth - width) / 2, 30 * scaleRatio / 2, width, height)

    let a = 20 * scaleRatio //定义行高
    context.setFontSize(15 * scaleRatio)
    context.setFillStyle("#343434")
    let w = 234 * scaleRatio
    //名称很长调用方法将文字折行，传参 文字内容text，画布context
    let row = poster.wrapText(text, Math.floor(w), context, 2)
    for (let i = 0; i < row.length; i++) {
      context.fillText(row[i], 15 * scaleRatio, 290 * scaleRatio + a * i)
    }
    context.setFillStyle("#EB0909")
    context.setFontSize(13 * scaleRatio)
    context.fillText('￥', 13 * scaleRatio, 340 * scaleRatio)
    let priceArr = Number(price).toFixed(2).toString().split('.')
    context.setFillStyle("#EB0909")
    context.setFontSize(13 * scaleRatio)
    context.fillText(priceArr[0], 28 * scaleRatio, 340 * scaleRatio)
    let w1 = poster.getTextWidth(priceArr[0], context) || 35
    context.setFontSize(13 * scaleRatio)
    context.setFillStyle("#EB0909")
    context.fillText(`.${priceArr[1]}`, 30 * scaleRatio + w1, 340 * scaleRatio)
    context.setFillStyle("#999999")
    context.setFontSize(12 * scaleRatio)
    let w2 = 38 * scaleRatio + w1 + (poster.getTextWidth(`.${priceArr[1]}`, context) || 32)
    context.fillText(`￥${originalPrice}`, w2, 340 * scaleRatio)
    context.moveTo(w2, 336 * scaleRatio)
    context.lineTo((w2 + 50 * scaleRatio), 336 * scaleRatio)
    context.setStrokeStyle('#999999')
    context.stroke(); //对当前路径进行描边
    // 识别小程序二维码 
    let x = winWidth - 88 * scaleRatio;
    context.drawImage(imgs.qrcode, x, 367 * scaleRatio, 65 * scaleRatio, 65 * scaleRatio)
    context.setFillStyle("#333")
    context.setFontSize(16 * scaleRatio)

    let w3 = 165 * scaleRatio
    //名称很长调用方法将文字折行，传参 文字内容text，画布context
    let row1 = poster.wrapText(name, Math.floor(w3), context, 1)
    for (let i = 0; i < row1.length; i++) {
      context.fillText(row1[i], 20 * scaleRatio, 390 * scaleRatio + a * i)
    }

    context.setFontSize(12 * scaleRatio)
    context.fillText('长按识别·立即体验', 20 * scaleRatio, 417 * scaleRatio)
    context.draw(false, () => {
      poster.createPoster(canvasId, winWidth, winHeight, (res) => {
        callback && callback(res)
      })
    })
  },
  //生成海报图片(分享所需图片)
  createPoster(canvasId, winWidth, winHeight, callback) {
    // let scaleRatio= wx.getSystemInfoSync().scaleRatio
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      // width: winWidth * scaleRatio,
      // height: Math.round(winHeight * scaleRatio),
      // destWidth: winWidth * scaleRatio,
      // destHeight: Math.round(winHeight) * scaleRatio,
      canvasId: canvasId,
      fileType: 'png',
      quality: 1,
      success: function (res) {
        callback && callback(res.tempFilePath)
      },
      fail() {
        callback && callback(false)
      }
    })
  },
  modal: function (callback, confirmColor, confirmText) {
    wx.showModal({
      title: '提示',
      content: '您还没有开启相册权限，是否立即设置？',
      showCancel: true,
      cancelColor: "#555",
      confirmColor: "#EB0909",
      confirmText: "确定",
      success(res) {
        if (res.confirm) {
          callback && callback(true)
        } else {
          callback && callback(false)
        }
      }
    })
  },
  //相册权限查询，如果没有权限则提示打开设置页面
  judgePermissionPhotoLibrary: async function (callback) {
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success() {
        callback && callback(true)
      },
      fail() {
        poster.modal((res) => {
          if (res) {
            wx.openSetting({
              success(res) {
                console.log(res.authSetting)
              }
            });
          }
        })
      }
    })
  },
  // 将海报图片保存到本地
  saveImage(file) {
    //检查是否授权相册权限
    poster.judgePermissionPhotoLibrary((res) => {
      //保存图片
      if (res) {
        wx.saveImageToPhotosAlbum({
          filePath: file,
          success(res) {
            wx.showToast({
              title: '图片保存成功',
              icon: 'none'
            })
          },
          fail(res) {
            wx.showToast({
              title: '图片保存失败',
              icon: 'none'
            })
          }
        })
      }
    })
  },
  //获取文本宽度(请先查看支持平台，App 端 2.8.12+ 支持)
  getTextWidth(text, context) {
    const metrics = context.measureText(text)
    return metrics.width || 0
  },
  //图片转成本地文件[同步执行]
  async getImage(url) {
    return await new Promise((resolve, reject) => {
      wx.downloadFile({
        url: url,
        success: res => {
          resolve(res.tempFilePath);
        },
        fail: res => {
          reject(false)
        }
      })
    })
  },
  //canvas多文字换行
  wrapText(text, width, context, rows = 2) {
    let txtArr = text.split('')
    let temp = ''
    let row = []
    for (let i = 0, len = txtArr.length; i < len; i++) {
      if (context.measureText(temp).width < width) {
        temp += txtArr[i]
      } else {
        i--
        row.push(temp)
        temp = ''
      }
    }
    row.push(temp)
    if (row.length > rows) {
      let rowCut = row.slice(0, rows);
      let rowPart = rowCut[rows - 1];
      let test = "";
      let empty = [];
      for (let j = 0, length = rowPart.length; j < length; j++) {
        if (context.measureText(test).width < width - 20) {
          test += rowPart[j];
        } else {
          break;
        }
      }
      empty.push(test);
      let group = empty[0] + "...";
      rowCut.splice(rows - 1, 1, group);
      row = rowCut;
    }
    return row
  },
  //删除已缓存文件，防止超出存储空间大小限制[同步执行]
  async removeSavedFile() {
    //使用前请先查看支持平台（其他方案：也可以先渲染出图片，当图片加载完成时执行相关方法）
    let count = 0;
    return await new Promise((resolve, reject) => {
      wx.getSavedFileList({
        success(res) {
          // console.log(res)
          count = res.fileList.length;
          if (count > 0) {
            let num = 0;
            let list = res.fileList || []
            list.forEach(item => {
              // console.log("执行删除文件。。。")
              wx.removeSavedFile({
                filePath: item.filePath,
                complete(res) {
                  num++;
                  if (num === count) {
                    resolve(true)
                  }
                }
              })
            })
          } else {
            resolve(true)
          }
        },
        fail() {
          reject(false)
          console.log("执行删除文件失败")
        }
      })
    })
  },
  //当服务器端返回图片base64时,转成本地文件[同步执行]
  async getImagebyBase64(base64) {
    //使用前先查看支持平台
    return await new Promise((resolve, reject) => {
      const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
      let arrayBuffer = wx.base64ToArrayBuffer(bodyData)
      //getuuid：注意这里名称需要动态生成（名称相同部分机型会出现写入失败，显示的是上次生成的图片）
      const filePath = `${wx.env.USER_DATA_PATH}/${poster.getuuid()}.${format}`;
      //此处可能会出现存储空间不足的情况，可清理缓存解决
      //fail the maximum size of the file storage limit is exceeded
      wx.getFileSystemManager().writeFile({
        filePath,
        data: arrayBuffer,
        encoding: 'binary',
        success() {
          resolve(filePath);
        },
        fail() {
          reject(false)
        }
      })
    })
  },
  getuuid() {
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
      return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
    });
    return uuid;
  }
}

module.exports = {
  drawPoster: poster.drawPoster,
  drawGoodsPoster: poster.drawGoodsPoster,
  getImage: poster.getImage,
  removeSavedFile: poster.removeSavedFile,
  getImagebyBase64: poster.getImagebyBase64,
  saveImage: poster.saveImage
};